package org.jeecg.modules.zcgl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.properties.config.JeecgPropertyConfig;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.system.service.IEncodingRulesService;
import org.jeecg.modules.zcgl.entity.*;
import org.jeecg.modules.zcgl.enums.*;
import org.jeecg.modules.zcgl.mapper.*;
import org.jeecg.modules.zcgl.service.IAssetContractLogService;
import org.jeecg.modules.zcgl.service.IAssetInfoService;
import org.jeecg.modules.zcgl.service.IAssetInfoSubService;
import org.jeecg.modules.zcgl.service.ILeaseContractInfoService;
import org.jeecg.modules.zcgl.tencent.service.IWxSendMessageService;
import org.jeecg.modules.zcgl.util.NoUtils;
import org.jeecg.modules.zcgl.vo.statistical.ContractParameterVo;
import org.jeecg.modules.zcgl.vo.LeaseContractInfoPage;
import org.jeecg.modules.zcgl.vo.LeaseContractRenewVo;
import org.jeecg.modules.zcgl.vo.statistical.DepositStatisticalVo;
import org.jeecg.modules.zcgl.vo.statistical.sum.ContractParameterSumVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 合同信息
 * @Author: jeecg-boot
 * @Date: 2020-06-20
 * @Version: V1.0
 */
@Service
@Transactional
public class LeaseContractInfoServiceImpl extends ServiceImpl<LeaseContractInfoMapper, LeaseContractInfo> implements ILeaseContractInfoService {

    @Autowired
    private IAssetInfoService assetInfoService;
    @Autowired
    private IAssetContractLogService assetContractLogService;
    @Resource
    private CustomerInfoMapper customerInfoMapper;
    @Autowired
    private IAssetInfoSubService assetInfoSubService;
    @Resource
    private ReceivablesInfoMapper receivablesInfoMapper;

    @Resource
    private PayablesInfoMapper payablesInfoMapper;
    @Resource
    private PayablesDetailsMapper payablesDetailsMapper;
    @Autowired
    private IWxSendMessageService sendMessageService;
    @Resource
    private LeaseContractStandardRentMapper leaseContractStandardRentMapper;
    @Resource
    private CustomerBalanceMapper customerBalanceMapper;
    @Autowired
    private IEncodingRulesService encodingRulesService;
    @Autowired
    private JeecgPropertyConfig jeecgPropertyConfig;

    @Override
    @Transactional
    public void saveMain(LeaseContractInfoPage leaseContractInfoPage) {
        this.checkModel(leaseContractInfoPage);
        LeaseContractInfo leaseContractInfo = new LeaseContractInfo();
        BeanUtils.copyProperties(leaseContractInfoPage, leaseContractInfo);
        this.saveOrUpdateMain(leaseContractInfo, leaseContractInfoPage.getLeaseContractStandardRentList());
    }

    private void saveOrUpdateMain(LeaseContractInfo leaseContractInfo, List<LeaseContractStandardRent> leaseContractStandardRentList) {

        /**
         * 重置审批信息
         */
        leaseContractInfo.setProcessStatus(-1);
        leaseContractInfo.setProcessDescription("");
        leaseContractInfo.setProcessStatusText("");

        boolean bool = super.saveOrUpdate(leaseContractInfo);

        if (!bool) {
            throw new JeecgBootException("更新失败！");
        }
        //1.先删除子表数据
        leaseContractStandardRentMapper.deleteByMainId(leaseContractInfo.getId());
        if (leaseContractStandardRentList != null && leaseContractStandardRentList.size() > 0) {
            for (LeaseContractStandardRent entity : leaseContractStandardRentList) {
                //外键设置
                entity.setLeaseContractId(leaseContractInfo.getId());
                entity.setCompanyId(leaseContractInfo.getCompanyId());
                entity.setSysOrgCode(leaseContractInfo.getSysOrgCode());
                leaseContractStandardRentMapper.insert(entity);
            }
        }
    }

    @Override
    @Transactional
    public void updateMain(LeaseContractInfoPage leaseContractInfoPage) {
        this.checkModel(leaseContractInfoPage);
        LeaseContractInfo leaseContractInfo = new LeaseContractInfo();
        BeanUtils.copyProperties(leaseContractInfoPage, leaseContractInfo);
        this.saveOrUpdateMain(leaseContractInfo, leaseContractInfoPage.getLeaseContractStandardRentList());
    }

    @Override
    @Transactional
    public void delMain(String id) {
        leaseContractStandardRentMapper.deleteByMainId(id);
        baseMapper.deleteById(id);
    }

    @Override
    @Transactional
    public void delBatchMain(Collection<? extends Serializable> idList) {
        for (Serializable id : idList) {
            leaseContractStandardRentMapper.deleteByMainId(id.toString());
            baseMapper.deleteById(id);
        }
    }

    @Transactional
    @Override
    public void autoGenerateReceivables(LeaseContractInfo leaseContractInfo) {
        //查询分段缴费信息
        List<LeaseContractStandardRent> leaseContractStandardRentList = leaseContractStandardRentMapper.selectByMainId(leaseContractInfo.getId());
        //生成收款信息
        this.computationalCosts(leaseContractInfo.getNextStartDate(), leaseContractInfo, -1, leaseContractStandardRentList);
        //更新合同信息
        boolean bool = super.updateById(leaseContractInfo);
        if (!bool) {
            throw new JeecgBootException("更新失败！");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void takeEffect(LeaseContractInfoPage page) {
        this.checkModel(page);
        this.update(page, false);
    }

    /**
     * 签订合同更新资产状态
     *
     * @param leaseContractInfo
     * @param startDate         开始日期
     */
    private void updateAssetStatus(LeaseContractInfo leaseContractInfo, Date startDate) {

        //把合同签订记录里面的合同设置为结束状态
        assetContractLogService.updateEnd(null, leaseContractInfo.getId(), null);

        List<String> assetIdList = Arrays.asList(leaseContractInfo.getAssetId().split(CommonConstant.DEFAULT_SEPARATOR));

        //根据资产IDS查询资产信息列表
        List<AssetInfo> assetInfoList = assetInfoService.listByIds(assetIdList);
        if (assetInfoList == null || assetIdList.size() != assetInfoList.size()) {
            throw new JeecgBootException("资产信息不存在");
        }

        //存资产明细IDS
        List<String> assetInfoSubIds = new ArrayList<>();
        if (StringUtils.isNotBlank(leaseContractInfo.getAssetSubIds())) {
            assetInfoSubIds = new ArrayList<>(Arrays.asList(leaseContractInfo.getAssetSubIds().split(CommonConstant.DEFAULT_SEPARATOR)));
        }
        //循环资产信息
        for (AssetInfo assetInfo : assetInfoList) {
            //查询资产的明细数量
            int assetInfoSubNo = assetInfoSubService.selectCountByMainId(assetInfo.getId());
            //如果资产有明细，但是合同没有选择资产明细信息抛出异常
            if (assetInfoSubNo > 0 && assetInfoSubService.selectCountByMainIdAndIds(assetInfo.getId(), leaseContractInfo.getAssetSubIds()) == 0) {
                throw new JeecgBootException(assetInfo.getAssetName() + "资产有资产明细，请填写资产明细");
            }
//            assetInfo.setEmptyReason("");
//            assetInfo.setConcreteIssue("");
            if (assetInfoSubNo > 0) {
                //循环判断资产房间信息并更新
                for (int i = 0; i < assetInfoSubIds.size(); ) {

                    AssetInfoSub sub = assetInfoSubService.getById(assetInfoSubIds.get(i));
                    if (sub == null) {
                        throw new JeecgBootException("有资产明细不存在");
                    }
//                    if (sub.getRoomStatus() != null && sub.getRoomStatus().compareTo(AssetStatusEnum.LEASE_OUT.getStatus()) == 0) {
//                        throw new JeecgBootException("有资产明细不是" + AssetStatusEnum.FOR_RENT.getName() + "，不能继续签订合同");
//                    }
                    //判断是否是当前资产
                    if (sub.getAssetInfoId().equalsIgnoreCase(assetInfo.getId())) {

                        //存入资产详情签订合同记录
                        assetContractLogService.creatorLog(sub.getAssetInfoId(), sub.getId(), startDate, leaseContractInfo);

                        sub.setLastRentEndTime(leaseContractInfo.getRentEndTime());
                        sub.setHasContractQuantity(sub.getHasContractQuantity() == null ? 1 : sub.getHasContractQuantity() + 1);
                        sub.setAllContractQuantity(sub.getAllContractQuantity() == null ? 1 : sub.getAllContractQuantity() + 1);
                        sub.setEmptyReason("");
                        sub.setConcreteIssue("");
                        sub.setRoomStatus(AssetStatusEnum.LEASE_OUT.getStatus());
                        assetInfoSubService.updateById(sub);
                        //该资产明细已经修改，从列表清除
                        assetInfoSubIds.remove(assetInfoSubIds.get(i));
                        assetInfo.setHasContractQuantity(assetInfo.getHasContractQuantity() == null ? 1 : assetInfo.getHasContractQuantity() + 1);
                        continue;
                    }
                    i++;
                }


                //查询未出租资产详情信息数量
                Integer num = assetInfoSubService.selectCountByRoomStatus(AssetStatusEnum.LEASE_OUT.getStatus(), assetInfo.getId());
                if (num == null || num.intValue() == 0) { //没有未出租的资产详情
                    assetInfo.setStatus(AssetStatusEnum.LEASE_OUT.getStatus());
                } else {
                    assetInfo.setStatus(AssetStatusEnum.PART_RENT.getStatus());
                }
                assetInfo.setAllContractQuantity(assetInfo.getAllContractQuantity() == null ? 1 : assetInfo.getAllContractQuantity() + 1);
            } else {
                assetInfo.setStatus(AssetStatusEnum.LEASE_OUT.getStatus());
                assetInfo.setLastRentEndTime(leaseContractInfo.getRentEndTime());
                assetInfo.setHasContractQuantity(assetInfo.getHasContractQuantity() == null ? 1 : assetInfo.getHasContractQuantity() + 1);
                assetInfo.setAllContractQuantity(assetInfo.getAllContractQuantity() == null ? 1 : assetInfo.getAllContractQuantity() + 1);
                //存入资产签订合同记录
                assetContractLogService.creatorLog(assetInfo.getId(), null, startDate, leaseContractInfo);
            }
        }

        //判断资产明细是否清空完成，如果未完成抛出异常
        if (assetInfoSubIds.size() > 0) {
            throw new JeecgBootException("有资产明细不是包含在资产信息里面！");
        }

        //更新资产状态
        assetInfoService.updateBatchById(assetInfoList);
    }

    @Override
    public void updateStatus(LeaseContractRenewVo vo) {

        this.updateStatusCheck(vo);

        LeaseContractInfo leaseContractInfo = baseMapper.selectById(vo.getId());
        leaseContractInfo.setStatus(vo.getStatus());

        if (vo.getStatus().compareTo(LeaseContractStatusEnum.TERMINATION.getStatus()) == 0) {

            this.changeAsset(leaseContractInfo.getAssetId(), leaseContractInfo.getAssetSubIds(), leaseContractInfo.getId());
            this.changeReceivablesInfo(leaseContractInfo.getId(), PayStatusEnum.UNPAID.getStatus(), PayStatusEnum.TERMINATE_CANCEL.getStatus());


            this.createPayablesInfo(vo, leaseContractInfo);
        } else if (vo.getStatus().compareTo(LeaseContractStatusEnum.SURRENDER.getStatus()) == 0) {

            this.changeAsset(leaseContractInfo.getAssetId(), leaseContractInfo.getAssetSubIds(), leaseContractInfo.getId());
            this.changeReceivablesInfo(leaseContractInfo.getId(), PayStatusEnum.UNPAID.getStatus(), PayStatusEnum.HIRE_CANCEL.getStatus());

            this.createPayablesInfo(vo, leaseContractInfo);
        } else if (vo.getStatus().compareTo(LeaseContractStatusEnum.TERMINATE.getStatus()) == 0) {
            if (leaseContractInfo.getRentEndTime().after(DateUtils.getDate())) {
                throw new JeecgBootException("合同还未到期，不能结束！");
            }

            this.changeAsset(leaseContractInfo.getAssetId(), leaseContractInfo.getAssetSubIds(), leaseContractInfo.getId());
//            this.changeReceivablesInfo(leaseContractInfo.getId(), PayStatusEnum.UNPAID.getStatus(), PayStatusEnum.HIRE_CANCEL.getStatus());

            this.createPayablesInfo(vo, leaseContractInfo);
        } else {
            throw new JeecgBootException("合同状态错误！");
        }


        if (leaseContractInfo.getRemark() == null) {
            leaseContractInfo.setRemark(vo.getRemark());
        } else if (StringUtils.isNotBlank(leaseContractInfo.getRemark())) {
            leaseContractInfo.setRemark(leaseContractInfo.getRemark() + vo.getRemark());
        }
        leaseContractInfo.setProcessStatus(-1);
        leaseContractInfo.setProcessStatusText("");
        baseMapper.updateById(leaseContractInfo);
    }

    @Override
    public void updateStatusCheck(LeaseContractRenewVo vo) {
        LeaseContractInfo leaseContractInfo = baseMapper.selectById(vo.getId());
        if (leaseContractInfo == null) {
            throw new JeecgBootException("未找到对应数据");
        }
        if (leaseContractInfo.getStatus() == null || (leaseContractInfo.getStatus().intValue() != 20 && leaseContractInfo.getStatus().intValue() != 30)) {
            throw new JeecgBootException("合同经营状态错误");
        }
    }

    @Override
    public boolean isHasByTo(LambdaQueryWrapper<LeaseContractInfo> queryWrapper) {
        queryWrapper.last("limit 1");
        List<LeaseContractInfo> list = baseMapper.selectList(queryWrapper);
        if (list != null && list.size() > 0) {
            return true;
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void modify(LeaseContractInfoPage leaseContractInfoPage) {
        this.check(leaseContractInfoPage, true);
        this.update(leaseContractInfoPage, true);
    }

    /**
     * 检测实体验证
     *
     * @param entity
     */
    @Override
    public void checkModel(LeaseContractInfoPage entity) {
        this.check(entity, false);
    }

    @Override
    public void modifyCheckModel(LeaseContractInfoPage leaseContractInfoPage) {
        LeaseContractInfo leaseContractInfo = baseMapper.selectById(leaseContractInfoPage.getId());
        if (leaseContractInfo == null) {
            throw new JeecgBootException("合同信息错误！");
        }
        this.check(leaseContractInfoPage, true);
        leaseContractInfoPage.setAssetSubIds(leaseContractInfo.getAssetSubIds());
        leaseContractInfoPage.setAssetId(leaseContractInfo.getAssetId());
    }

    @Override
    public void renewCheckModel(LeaseContractRenewVo vo) {
        if (vo.getEndDate() == null) {
            throw new JeecgBootException("续签的到期日期必须填写！");
        }
        LeaseContractInfo leaseContractInfo = baseMapper.selectById(vo.getId());
        if (leaseContractInfo == null) {
            throw new JeecgBootException("合同信息错误！");
        }
        if (leaseContractInfo.getRentEndTime() == null || vo.getEndDate() == null || DateUtils.sameDate(leaseContractInfo.getRentEndTime(), vo.getEndDate()) > -1) {
            throw new JeecgBootException("续签日期必须在原日期之后");
        }
        LeaseContractInfoPage entity = new LeaseContractInfoPage();
        BeanUtils.copyProperties(leaseContractInfo, entity);
        entity.setLeaseContractStandardRentList(vo.getLeaseContractStandardRentList());
        entity.setRentStartTime(DateUtils.nextDay(leaseContractInfo.getRentEndTime(), 1));
        entity.setRentEndTime(vo.getEndDate());

        String[] assetIdStr = entity.getAssetId().split(CommonConstant.DEFAULT_SEPARATOR);
        Arrays.stream(assetIdStr).forEach(assetId -> {
            AssetInfo assetInfo = assetInfoService.getById(assetId);
            if (assetInfo == null) {
                throw new JeecgBootException("有资产不存在");
            }
            int subNum = assetInfoSubService.selectCountByMainId(assetInfo.getId());
            if (subNum == 0 && assetInfo.getLastRentEndTime() != null && DateUtils.sameDate(leaseContractInfo.getRentEndTime(), assetInfo.getLastRentEndTime()) != 0) {
                throw new JeecgBootException(assetInfo.getAssetName() + "资产已重新出租不能续签！");
            }
            if (StringUtils.isBlank(entity.getAssetSubIds())) {
                if (subNum > 0) {
                    throw new JeecgBootException(assetInfo.getAssetName() + "资产有资产明细，请填写资产明细");
                }
            } else {
                if (subNum > 0 && assetInfoSubService.selectCountByMainIdAndIds(assetInfo.getId(), entity.getAssetSubIds()) == 0) {
                    throw new JeecgBootException(assetInfo.getAssetName() + "资产有资产明细，请填写资产明细");
                }
            }
        });
        if (StringUtils.isNotBlank(entity.getAssetSubIds())) {
            String[] assetSubIdStr = entity.getAssetSubIds().split(CommonConstant.DEFAULT_SEPARATOR);
            Arrays.stream(assetSubIdStr).forEach(assetSubId -> {
                AssetInfoSub assetInfoSub = assetInfoSubService.getById(assetSubId);
                if (assetInfoSub == null) {
                    throw new JeecgBootException("有资产明细不存在");
                }
                if (assetInfoSub.getLastRentEndTime() != null && DateUtils.sameDate(leaseContractInfo.getRentEndTime(), assetInfoSub.getLastRentEndTime()) != 0) {
                    throw new JeecgBootException(assetInfoSub.getRoomName() + "资产明细已重新出租不能续签！");
                }

            });
        }
        this.check(entity, true);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void renew(LeaseContractRenewVo vo) {
        this.renewCheckModel(vo);
        LeaseContractInfo leaseContractInfo = baseMapper.selectById(vo.getId());
        Date startDate = DateUtils.nextDay(leaseContractInfo.getRentEndTime(), 1);

        leaseContractInfo.setRentEndTime(vo.getEndDate());
        leaseContractInfo.setMonthlyRent(vo.getMonthlyRent());
        leaseContractInfo.setStatus(LeaseContractStatusEnum.RENEW.getStatus());
        //修改资产状态
        this.updateAssetStatus(leaseContractInfo, leaseContractInfo.getRentStartTime());

        //生成费用
        this.computationalCosts(startDate, leaseContractInfo, LeaseContractStatusEnum.RENEW.getStatus(), vo.getLeaseContractStandardRentList());


        List<LeaseContractStandardRent> standardRentList = leaseContractStandardRentMapper.selectByMainId(leaseContractInfo.getId());
        if (standardRentList != null && standardRentList.size() > 0) {
            if (vo.getLeaseContractStandardRentList() != null) {
                standardRentList.addAll(vo.getLeaseContractStandardRentList());
            }
        } else {
            standardRentList = vo.getLeaseContractStandardRentList();
        }
        this.saveOrUpdateMain(leaseContractInfo, standardRentList);

    }

    @Override
    public void importSaveMain(LeaseContractInfoPage vo) {

        if (StringUtils.isNotBlank(vo.getAssetSubIds()) && StringUtils.isNotBlank(vo.getAssetId())) {
            List<String> names = new ArrayList<>();
            List<String> subIds = Arrays.asList(vo.getAssetSubIds().split(CommonConstant.DEFAULT_SEPARATOR));
            List<AssetInfoSub> list = assetInfoSubService.listByIds(subIds);
            if (list == null || subIds.size() != list.size()) {
                throw new JeecgBootException("有资产明细不存在");
            }
            for (AssetInfoSub sub : list) {
                names.add(sub.getRoomName());
            }
            QueryWrapper<AssetInfoSub> queryWrapper = new QueryWrapper<>();
//            queryWrapper.lambda().eq(AssetInfoSub::getAssetInfoId, vo.getAssetId());
            queryWrapper.lambda().in(AssetInfoSub::getAssetInfoId, vo.getAssetId().split(CommonConstant.DEFAULT_SEPARATOR));
            queryWrapper.lambda().in(AssetInfoSub::getRoomName, names);
            List<AssetInfoSub> subs = assetInfoSubService.list(queryWrapper);
            names.clear();
            if (subs != null) {
                subs.forEach(s -> {
                    names.add(s.getId());
                });
            }
            vo.setAssetSubIds(StringUtils.join(names, CommonConstant.DEFAULT_SEPARATOR));
        }
        vo.setStatus(LeaseContractStatusEnum.DRAFT.getStatus());

        this.checkModel(vo);

        LeaseContractInfo leaseContractInfo = new LeaseContractInfo();
        BeanUtils.copyProperties(vo, leaseContractInfo);
        this.saveOrUpdateMain(leaseContractInfo, vo.getLeaseContractStandardRentList());
    }

    @Override
    public IPage<ContractParameterVo> queryContractParameterVoList(Page<ContractParameterVo> page, QueryWrapper<ContractParameterVo> queryWrapper) {
        return baseMapper.queryContractParameterVoList(page,queryWrapper);
    }

    @Override
    public List<ContractParameterVo> queryContractParameterVoList(QueryWrapper<ContractParameterVo> queryWrapper) {
        return baseMapper.queryContractParameterVoList(queryWrapper);
    }

    @Override
    public IPage<DepositStatisticalVo> queryDepositStatisticalVoList(Page<DepositStatisticalVo> page, QueryWrapper<DepositStatisticalVo> queryWrapper) {
        return baseMapper.queryDepositStatisticalVoList(page,queryWrapper);
    }

    @Override
    public List<DepositStatisticalVo> queryDepositStatisticalVoList(QueryWrapper<DepositStatisticalVo> queryWrapper) {
        return baseMapper.queryDepositStatisticalVoList(queryWrapper);
    }

    @Override
    public ContractParameterSumVo getContractParameterSum(QueryWrapper<ContractParameterVo> queryWrapper) {
        return baseMapper.getContractParameterSum(queryWrapper);
    }


    private void createPayablesInfo(LeaseContractRenewVo vo, LeaseContractInfo leaseContractInfo) {
        BigDecimal totalMoney = BigDecimal.ZERO;
        List<PayablesDetails> payablesDetailsList = new ArrayList<>();
        //如果有押金退回，添加押金记录
        if (vo.getCashDeposit() != null && vo.getCashDeposit().compareTo(BigDecimal.ZERO) > 0) {
            totalMoney = totalMoney.add(vo.getCashDeposit());
            PayablesDetails payablesDetails = new PayablesDetails();
            payablesDetails.setAmountMoney(vo.getCashDeposit());
            payablesDetails.setPaymentInstructions(PaymentInstructionsEnum.CAUTION_MONEY.getStatus());
            payablesDetailsList.add(payablesDetails);
        }
        //如果有租金退回添加租金记录
        if (vo.getRent() != null && vo.getRent().compareTo(BigDecimal.ZERO) > 0) {
            totalMoney = totalMoney.add(vo.getRent());
            PayablesDetails payablesDetails = new PayablesDetails();
            payablesDetails.setAmountMoney(vo.getRent());
            payablesDetails.setPaymentInstructions(PaymentInstructionsEnum.RENT.getStatus());
            payablesDetailsList.add(payablesDetails);
        }
        if (payablesDetailsList.size() > 0) {
            //如果有退回，生成应付款项
            PayablesInfo payablesInfo = new PayablesInfo();
            payablesInfo.setPayablesNo(NoUtils.getPayablesNo());
            payablesInfo.setPayStatus(PaymentStatusEnum.UNPAID.getStatus());
            payablesInfo.setTotalMoney(totalMoney);
            payablesInfo.setCustomerId(leaseContractInfo.getCustomerId());
            payablesInfo.setLeaseContractId(leaseContractInfo.getId());
            payablesInfo.setAssetId(leaseContractInfo.getAssetId());
            payablesInfo.setAssetSubIds(leaseContractInfo.getAssetSubIds());
            payablesInfoMapper.insert(payablesInfo);

            //插入退款信息详情
            payablesDetailsList.stream().forEach(payablesDetails -> {
                payablesDetails.setPayablesInfoId(payablesInfo.getId());
                payablesDetails.setCustomerId(leaseContractInfo.getCustomerId());
                payablesDetails.setLeaseContractId(leaseContractInfo.getId());
                payablesDetails.setAssetId(leaseContractInfo.getAssetId());
                payablesDetails.setAssetSubIds(leaseContractInfo.getAssetSubIds());
                payablesDetailsMapper.insert(payablesDetails);
            });
        }

    }

    /**
     * 结束、退租或者终止后修改资产状态
     *
     * @param assetId
     * @param assetSubIds
     */
    private void changeAsset(String assetId, String assetSubIds, String leaseContractId) {

        if (StringUtils.isNotBlank(leaseContractId)) {
            //把合同签订记录里面的合同设置为结束状态
            assetContractLogService.updateEnd(null, leaseContractId, null);
        }
        assetInfoService.updateAssetForRentStatus(assetId, assetSubIds);
    }

    /**
     * 退租或者终止后修改应付款项状态
     *
     * @param status
     * @param payStatus
     */
    private void changeReceivablesInfo(String leaseContractId, Integer status, final Integer payStatus) {

        QueryWrapper<ReceivablesInfo> qw = new QueryWrapper<>();
        ReceivablesInfo receivablesInfo = new ReceivablesInfo();
        receivablesInfo.setPayStatus(status);
        receivablesInfo.setLeaseContractId(leaseContractId);
        qw.setEntity(receivablesInfo);
        List<ReceivablesInfo> receivablesInfoList = receivablesInfoMapper.selectList(qw);
        receivablesInfoList.stream().forEach(receivables -> {
            receivables.setPayStatus(payStatus);
            receivablesInfoMapper.updateById(receivables);
        });
    }

    /**
     * 计算应收款项
     *
     * @param startDate
     * @param leaseContractInfo
     */
    private void computationalCosts(Date startDate, LeaseContractInfo leaseContractInfo, int status, List<LeaseContractStandardRent> leaseContractStandardRentList) {

        //根据租金支付方式计算支付周期的月数量
        int m = ModeOfPaymentTypeEnum.getMonth(leaseContractInfo.getModeOfPayment());

        //计算每期的基本租金信息
        BigDecimal leaseAmountMoney = leaseContractInfo.getMonthlyRent().multiply(new BigDecimal(m));
        /**最后的结束日期**/
        Date lastEndDate = null;
        /**最后的开始日期**/
        Date lastStartDate = startDate;
        /**最后的付款日期**/
        Date payStartDate = null;
        boolean isFirst = true;
        int rentSize = leaseContractStandardRentList == null ? 0 : leaseContractStandardRentList.size();
        boolean isWhile = true;
        do {

            if (isFirst && status == LeaseContractStatusEnum.TAKE_EFFECT.getStatus()) {
                payStartDate = leaseContractInfo.getSigningDate();
                isFirst = false;
            } else {
                payStartDate = DateUtils.nextDay(lastStartDate, 0 - leaseContractInfo.getBeforeDay());
            }

            //当付款开始日期大于当前日期，则不生成后面的账单
            if (DateUtils.sameDate(payStartDate, DateUtils.getDate()) > 0) {
                leaseContractInfo.setNextRentStartTime(payStartDate);
                leaseContractInfo.setNextStartDate(lastStartDate);
                leaseContractInfo.setIzGenerateComplete(YesNoEnum.NO.getStatus());
                break;
            }

            lastEndDate = DateUtils.nextDay(DateUtils.nextMonth(lastStartDate, m), -1);
            if (DateUtils.sameDate(lastEndDate, leaseContractInfo.getRentEndTime()) > 0) {
                if (rentSize == 0) {
                    leaseAmountMoney = calculateMoney(lastStartDate, leaseContractInfo.getRentEndTime(), BigDecimal.ZERO, leaseContractInfo.getMonthlyRent());
                }
                lastEndDate = leaseContractInfo.getRentEndTime();
            }

            if (rentSize > 0) {
                leaseAmountMoney = this.calculateLeaseAmountMoney(lastStartDate, lastEndDate, leaseContractInfo, leaseContractStandardRentList, m);
            }
            this.createReceivablesInfo(leaseContractInfo, leaseContractInfo.getAssetId(), leaseContractInfo.getAssetSubIds(), leaseContractInfo.getCustomerId(),
                    PaymentInstructionsEnum.RENT.getStatus(), leaseAmountMoney,
                    lastStartDate, lastEndDate, payStartDate, "");
            lastStartDate = DateUtils.nextDay(lastEndDate, 1);

            if (DateUtils.sameDate(lastStartDate, leaseContractInfo.getRentEndTime()) != -1) {
                leaseContractInfo.setIzGenerateComplete(YesNoEnum.YES.getStatus());
                isWhile = false;
            }
        } while (isWhile);

    }

    BigDecimal calculateLeaseAmountMoney(Date startTime, Date endTime, LeaseContractInfo leaseContractInfo,
                                         List<LeaseContractStandardRent> leaseContractStandardRentList, int month) {
        BigDecimal leaseAmountMoney = BigDecimal.ZERO;

        Date newStartTime = startTime;
        Date newEndTime = endTime;

        //计算付款周期的总天数
        int totalDay = DateUtils.daysBetween(newStartTime, newEndTime);
        for (LeaseContractStandardRent rent : leaseContractStandardRentList) {
            //比较该段结束日期和开始日期
            int a = DateUtils.sameDate(rent.getRentEndTime(), newStartTime);
            //开始日期在该段结束日期之后，直接返回
            if (a != 1) {
                continue;
            }
            //比较该段开始日期和开始日期
            int b = DateUtils.sameDate(rent.getStartTime(), newStartTime);
            //开始日期在该段开始日期之前
            if (b == 1) {
                //比较该段开始日期和结束日期
                int c = DateUtils.sameDate(rent.getStartTime(), newEndTime);
                //如果结束时间在该段开始之前，直接计算
                if (c != -1) {
                    break;
                }
                leaseAmountMoney = this.calculateMoney(newStartTime, DateUtils.nextDay(rent.getStartTime(), -1), leaseAmountMoney, leaseContractInfo.getMonthlyRent());
                newStartTime = rent.getStartTime();

            }
            int d = DateUtils.sameDate(rent.getRentEndTime(), newEndTime);
            //如果结束时间在该段的结束日期之前，计算前面
            if (d != -1) {

                if (DateUtils.sameDate(newStartTime, startTime) == 0) {
                    leaseAmountMoney = rent.getMonthlyPrice().multiply(new BigDecimal(month));
                } else {
                    leaseAmountMoney = this.calculateMoney(newStartTime, newEndTime, leaseAmountMoney, rent.getMonthlyPrice());
                }
                newStartTime = newEndTime;
                break;
            } else {
                //如果结束日期在该段结束日期之后，计算该段的全部金额
                leaseAmountMoney = this.calculateMoney(newStartTime, rent.getRentEndTime(), leaseAmountMoney, rent.getMonthlyPrice());
                //把开始日期设置为该段的结束日期
                newStartTime = DateUtils.nextDay(rent.getRentEndTime(), 1);
                continue;
            }

        }
        if (DateUtils.sameDate(newStartTime, newEndTime) == -1) {
            if (DateUtils.sameDate(newStartTime, startTime) == 0) {
                leaseAmountMoney = leaseContractInfo.getMonthlyRent().multiply(new BigDecimal(month));
            } else {
                leaseAmountMoney = this.calculateMoney(newStartTime, newEndTime, leaseAmountMoney, leaseContractInfo.getMonthlyRent());
            }
        }
        return leaseAmountMoney;
    }

    /**
     * 计算租金
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param old       原来的租金
     * @param monthRent 月租金
     * @return
     */
    private static BigDecimal calculateMoney(Date startTime, Date endTime, BigDecimal old, BigDecimal monthRent) {

        //2个日期之间相差的月份数量
        int m = DateUtils.monthsBetween(startTime, endTime);
        /** 计算完整的月份租金*/
        BigDecimal bigDecimal = monthRent.multiply(new BigDecimal(m));
        //新的开始日期
        Date newStartTime = DateUtils.nextDay(DateUtils.nextMonth(startTime, m), -1);
        if (DateUtils.sameDate(newStartTime, endTime) != 0) {
            //计算2个日期之间实际的总天数
            int d1 = DateUtils.daysBetween(newStartTime, endTime);
            //计算当月的实际天数（如果总天数大于0就以结束日期所在月份计算，否则以开始日期的月份计算）
            int maxDay = d1 > 0 ? DateUtils.getMaxDay(endTime) : DateUtils.getMaxDay(startTime);
            //如果2个日期之间的实际天数等于月的总天数计算整月，否则计算一天的租金*天数
            if (d1 == maxDay) {
                bigDecimal = bigDecimal.add(monthRent);
            } else {
                bigDecimal = bigDecimal.add(monthRent.divide(new BigDecimal(maxDay), 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(d1)));
            }
        }
        return old.add(bigDecimal);
    }


    /**
     * 生成插入应收款项
     *
     * @param leaseContract
     * @param assetId
     * @param customerId
     * @param paymentInstructions
     * @param amountMoney
     * @param startTime
     * @param endTime
     * @param remark
     */
    private ReceivablesInfo createReceivablesInfo(LeaseContractInfo leaseContract, String assetId, String assetSubIds, String customerId,
                                                  Integer paymentInstructions, BigDecimal amountMoney,
                                                  Date startTime, Date endTime, Date payStartDate, String remark) {
        ReceivablesInfo receivablesInfo = new ReceivablesInfo();
        receivablesInfo.setLeaseContractId(leaseContract.getId());
        receivablesInfo.setAssetId(assetId);
        receivablesInfo.setAssetSubIds(assetSubIds);
        receivablesInfo.setCustomerId(customerId);
        receivablesInfo.setPaymentInstructions(paymentInstructions);
        if (amountMoney == null || amountMoney.compareTo(BigDecimal.ZERO) <= 0) {
//            amountMoney = new BigDecimal(0.01);
            throw new JeecgBootException("款项金额必须大于0！");
        }
        receivablesInfo.setAmountMoney(amountMoney);
        receivablesInfo.setUnAmountMoney(amountMoney);
        receivablesInfo.setPaidAmountMoney(BigDecimal.ZERO);
        receivablesInfo.setPayStatus(PayStatusEnum.UNPAID.getStatus());
        receivablesInfo.setStartTime(startTime);
        receivablesInfo.setEndTime(endTime);
        receivablesInfo.setPayStartDate(payStartDate);
        receivablesInfo.setAmountConfirmation(YesNoEnum.NO.getStatus());
        receivablesInfo.setRemark(remark);
        receivablesInfo.setCompanyId(leaseContract.getCompanyId());
        receivablesInfo.setSysOrgCode(leaseContract.getSysOrgCode());
        //合同的出租方，就是收款信息的入账公司
        receivablesInfo.setRentCompanyId(leaseContract.getRentCompanyId());
        boolean bool = super.retBool(receivablesInfoMapper.insert(receivablesInfo));

        if (bool && !receivablesInfo.getPayStartDate().after(new Date())) {
            try {
                sendMessageService.paymentReminder(receivablesInfo.getId());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return receivablesInfo;
    }


    private String getContractNum(LeaseContractInfo leaseContractInfo) {
        return encodingRulesService.getNextCoding(YesNoEnum.NO.getStatus(), null, null,
                jeecgPropertyConfig.getLeaseContractNumRules(), leaseContractInfo.getCompanyId());
    }

    /**
     * @param page
     * @param isModify 是否是合同变更，如果是合同变更忽略资产信息
     */
    public void update(LeaseContractInfoPage page, boolean isModify) {

        LeaseContractInfo leaseContractInfo = new LeaseContractInfoPage();
        BeanUtils.copyProperties(page, leaseContractInfo);
        //设置默认为季度付
        if (leaseContractInfo.getModeOfPayment() == null) {
            leaseContractInfo.setModeOfPayment(ModeOfPaymentTypeEnum.PAY_QUARTERLY.getStatus());
        }
        //设置默认提前7天付款
        if (leaseContractInfo.getBeforeDay() == null) {
            leaseContractInfo.setBeforeDay(20);
        }
        //设置默认签约日期为当前日期
        if (leaseContractInfo.getSigningDate() == null) {
            leaseContractInfo.setSigningDate(new Date());
        }
        if (StringUtils.isBlank(leaseContractInfo.getAssetSubIds())) {
            leaseContractInfo.setAssetSubIds(null);
        }
        if (!isModify && leaseContractInfo.getStatus().intValue() != LeaseContractStatusEnum.TAKE_EFFECT.getStatus()) {
            throw new JeecgBootException("合同状态错误！");
        }

        //清除审批流程信息
        leaseContractInfo.setProcessStatus(-1);
        leaseContractInfo.setProcessDescription("");
        leaseContractInfo.setProcessStatusText("");

        this.updateAssetStatus(leaseContractInfo, leaseContractInfo.getRentStartTime());

        if (isModify){
            //更新合同信息
            this.saveOrUpdateMain(leaseContractInfo, page.getLeaseContractStandardRentList());
        } else {
            //判断是否有保证金，如果有保证金添加保证金收款信息
//            if (leaseContractInfo.getCashDeposit() != null && leaseContractInfo.getCashDeposit().compareTo(BigDecimal.ZERO) > 0) {
//                this.createReceivablesInfo(leaseContractInfo, leaseContractInfo.getAssetId(), leaseContractInfo.getAssetSubIds(), leaseContractInfo.getCustomerId(),
//                        PaymentInstructionsEnum.CAUTION_MONEY.getStatus(), leaseContractInfo.getCashDeposit(),
//                        leaseContractInfo.getRentStartTime(), leaseContractInfo.getRentEndTime(), leaseContractInfo.getSigningDate(), "");
//            }

            //如果固定计费，生成收款信息
            if (leaseContractInfo.getChargeType().intValue() == LeaseContractChargeTypeEnum.FIXED_PRICING.getStatus()) {

                //默认开始日期为合同开始日期
                Date startDate = leaseContractInfo.getRentStartTime();
                //判断是否有免租期，如果有免租期重置开始日期为免租期结束后
//            if (leaseContractInfo.getRentHolidayDay() != null && leaseContractInfo.getRentHolidayDay().intValue() != 0) {
//                startDate = DateUtils.nextMonth(startDate, leaseContractInfo.getRentHolidayDay());
//            }
                if (leaseContractInfo.getRentHolidayEnd() != null) {
                    startDate = DateUtils.nextDay(leaseContractInfo.getRentHolidayEnd(), 1);
                }

                //生成收款信息
                this.computationalCosts(startDate, leaseContractInfo, LeaseContractStatusEnum.TAKE_EFFECT.getStatus(), page.getLeaseContractStandardRentList());
            }
            leaseContractInfo.setTotalBalance(BigDecimal.ZERO);
            //更新合同信息
            baseMapper.updateById(leaseContractInfo);
        }

        //合同生效后，检测客户有没有该合同的余额信息，没有就生成余额信息。
        if (StringUtils.isNotBlank(leaseContractInfo.getCustomerId())
                && StringUtils.isNotBlank(leaseContractInfo.getRentCompanyId())) {
            String[] customerIdArr = leaseContractInfo.getCustomerId().split(CommonConstant.DEFAULT_SEPARATOR);
            for (String customerId : customerIdArr) {
                CustomerBalance customerBalance = customerBalanceMapper.selectCustomerIdAndLeaseContractId(leaseContractInfo.getId(), customerId);
                if (customerBalance == null) {
                    customerBalance = new CustomerBalance();
                    customerBalance.setCustomerId(customerId);
                    customerBalance.setCompanyId(leaseContractInfo.getRentCompanyId());
                    customerBalance.setLeaseContractId(leaseContractInfo.getId());
                    customerBalance.setBalance(BigDecimal.ZERO);
                    customerBalanceMapper.insert(customerBalance);
                }
            }
        }
    }

    /**
     * @param entity
     * @param isModify 是否是合同变更，如果是合同变更忽略资产信息
     */
    private void check(LeaseContractInfoPage entity, boolean isModify) {

        if (entity.getRentStartTime() == null) {
            throw new JeecgBootException("请选择起租时间！");
        }
        if (entity.getRentEndTime() == null) {
            entity.setRentEndTime(DateUtils.nextDay(DateUtils.nextYear(entity.getRentStartTime(), 200), -1));
//            return "请选择到租时间";
        }
        if ((entity.getMonthlyRent() == null || entity.getMonthlyRent().compareTo(BigDecimal.ZERO) < 0) &&
                (entity.getLeaseContractStandardRentList() == null || entity.getLeaseContractStandardRentList().size() == 0)) {
            throw new JeecgBootException("请填写租金！");
        }
        if (DateUtils.sameDate(entity.getRentStartTime(), entity.getRentEndTime()) > -1) {
            throw new JeecgBootException("起租时间【" + DateUtils.formatDate(entity.getRentStartTime()) + "】必须在到租时间【" + DateUtils.formatDate(entity.getRentEndTime()) + "】之前");
        }
        if (StringUtils.isNotBlank(entity.getRentHolidayDay())) {
            if (entity.getRentHolidayStart() == null) {
                entity.setRentHolidayStart(entity.getRentStartTime());
            }
            if (entity.getRentHolidayEnd() == null) {
                throw new JeecgBootException("请填写免租结束日期！");
            }
        }
        if (entity.getRentHolidayStart() != null || entity.getRentHolidayEnd() != null) {
            if (StringUtils.isBlank(entity.getRentHolidayDay())) {
                throw new JeecgBootException("请填写免租期限！");
            }
        }
        if (entity.getRentHolidayStart() != null && entity.getRentHolidayEnd() != null) {
            if (DateUtils.sameDate(entity.getRentStartTime(), entity.getRentHolidayStart()) != 0) {
                throw new JeecgBootException("免租开始日期必须是起租时间！");
            }
            if (DateUtils.sameDate(entity.getRentHolidayEnd(), entity.getRentEndTime()) > 0) {
                throw new JeecgBootException("免租结束日期必须在到租时间之前！");
            }
        } else if (entity.getRentHolidayStart() != null) {
            throw new JeecgBootException("请填写免租结束日期！");
        } else if (entity.getRentHolidayEnd() != null) {
            entity.setRentHolidayStart(entity.getRentStartTime());
        }
//        if (entity.getRentHolidayDay() != null && entity.getRentHolidayDay().intValue() != 0) {
//            entity.setRentHolidayStart(entity.getRentStartTime());
//            entity.setRentHolidayEnd(DateUtils.nextDay(DateUtils.nextMonth(entity.getRentHolidayStart(), entity.getRentHolidayDay()), -1));
//            if (DateUtils.sameDate(entity.getRentHolidayEnd(), entity.getRentEndTime()) > 0) {
//                throw new JeecgBootException("免租结束日期不能在到租时间之前！");
//            }
//        }
        if (StringUtils.isBlank(entity.getAssetId())) {
            throw new JeecgBootException("请填写正确的资产信息！");
        }
        if (StringUtils.isBlank(entity.getCustomerId())) {
            throw new JeecgBootException("请填写正确的客户信息！");
        }
        if (StringUtils.isBlank(entity.getRentCompanyId())) {
            throw new JeecgBootException("请选择出租方！");
        }


        boolean codeBool;
        boolean isAuto = false;
        if (StringUtils.isBlank(entity.getContractNum())) {
            isAuto = true;
            entity.setContractNum(this.getContractNum(entity));
        }
        //循环获取没有重复的编码
        do {
            LambdaQueryWrapper<LeaseContractInfo> queryWrapper = new LambdaQueryWrapper<>();
            if (StringUtils.isNotBlank(entity.getId())) {
                queryWrapper.ne(LeaseContractInfo::getId, entity.getId());
            }
            queryWrapper.eq(LeaseContractInfo::getContractNum, entity.getContractNum());
            queryWrapper.last("LIMIT 1");
            LeaseContractInfo v = this.getOne(queryWrapper);
            if (v != null) {
                if (!isAuto) {
                    throw new JeecgBootException("【" + entity.getContractNum() + "】合同编号已存在");
                }
                entity.setContractNum(this.getContractNum(entity));
                codeBool = true;
            } else {
                codeBool = false;
            }
        } while (codeBool && isAuto);
        if (entity.getStatus() == null || entity.getStatus() == 0) {
            entity.setStatus(LeaseContractStatusEnum.DRAFT.getStatus());
        }
        if (entity.getBeforeDay() == null) {
            entity.setBeforeDay(20);
        }
        if (!isModify) {
            String[] assetIdStr = entity.getAssetId().split(CommonConstant.DEFAULT_SEPARATOR);
            Arrays.stream(assetIdStr).forEach(assetId -> {
                AssetInfo assetInfo = assetInfoService.getById(assetId);
                if (assetInfo == null) {
                    throw new JeecgBootException("有资产不存在");
                }
                int subNum = assetInfoSubService.selectCountByMainId(assetInfo.getId());
                if (subNum == 0 && assetInfo.getStatus() != null &&
                        assetInfo.getStatus().intValue() != AssetStatusEnum.FOR_RENT.getStatus() &&
                        assetInfo.getStatus().intValue() != AssetStatusEnum.PART_RENT.getStatus()) {
                    throw new JeecgBootException(assetInfo.getAssetName() + "资产不是闲置状态！");
                }
//                if (DateUtils.sameDate(entity.getRentStartTime(), assetInfo.getLastRentEndTime()) < 1) {
//                    throw new JeecgBootException(assetInfo.getAssetName() + "资产合同开始日期在资产上一个合同的结束日期之前！");
//                }
                if (StringUtils.isBlank(entity.getAssetSubIds())) {
                    if (subNum > 0) {
                        throw new JeecgBootException(assetInfo.getAssetName() + "资产有资产明细，请填写资产明细");
                    }
                } else {
                    if (subNum > 0 && assetInfoSubService.selectCountByMainIdAndIds(assetInfo.getId(), entity.getAssetSubIds()) == 0) {
                        throw new JeecgBootException(assetInfo.getAssetName() + "资产有资产明细，请填写资产明细");
                    }
                }
            });
            if (StringUtils.isNotBlank(entity.getAssetSubIds())) {
                String[] assetSubIdStr = entity.getAssetSubIds().split(CommonConstant.DEFAULT_SEPARATOR);
                Arrays.stream(assetSubIdStr).forEach(assetSubId -> {
                    AssetInfoSub assetInfoSub = assetInfoSubService.getById(assetSubId);
                    if (assetInfoSub == null) {
                        throw new JeecgBootException("有资产明细不存在");
                    }
                    if (assetInfoSub.getRoomStatus() != null &&
                            assetInfoSub.getRoomStatus().intValue() != AssetStatusEnum.FOR_RENT.getStatus()
                    ) {
                        throw new JeecgBootException(assetInfoSub.getRoomName() + "资产详情不是闲置状态！");
                    }
//                    if (DateUtils.sameDate(entity.getRentStartTime(), assetInfoSub.getLastRentEndTime()) < 1) {
//                        throw new JeecgBootException(assetInfoSub.getRoomName() + "资产详情合同开始日期在资产上一个合同的结束日期之前！");
//                    }

                });
            }
        }
        String[] customerIdStr = entity.getCustomerId().split(CommonConstant.DEFAULT_SEPARATOR);
        Arrays.stream(customerIdStr).forEach(customerId -> {
            if (customerInfoMapper.selectById(customerId) == null) {
                throw new JeecgBootException("有承租人不存在");
            }
        });

        if (entity.getLeaseContractStandardRentList() != null && entity.getLeaseContractStandardRentList().size() > 0) {

            List<LeaseContractStandardRent> filter = entity.getLeaseContractStandardRentList().stream()
                    .filter(rent -> rent.getStartTime() != null || rent.getRentEndTime() != null || rent.getMonthlyPrice() != null)
                    .collect(Collectors.toList());
            filter.sort((o1, o2) -> DateUtils.sameDate(o1.getStartTime(), o2.getStartTime()));
            int i = 0;
            for (LeaseContractStandardRent rent : filter) {

//                if (rent.getStartTime()==null && rent.getRentEndTime() == null && rent.getMonthlyPrice() == null){
//                    entity.getLeaseContractStandardRentList().remove(entity);
//                    continue;
//                }
                if (rent.getPaymentInstructions() == null) {
                    rent.setPaymentInstructions(PaymentInstructionsEnum.RENT.getStatus());
                }
                if (rent.getStartTime() == null) {
                    throw new JeecgBootException("请填写分段租金开始日期！");
                }
                if (rent.getRentEndTime() == null) {
                    throw new JeecgBootException("请填写分段租金结束日期！");
                }
                if (DateUtils.sameDate(rent.getStartTime(), rent.getRentEndTime()) > -1) {
                    throw new JeecgBootException("分段租金开始日期必须在结束日期之前！");
                }
                if (rent.getMonthlyPrice() == null || BigDecimal.ZERO.compareTo(rent.getMonthlyPrice()) >= 0) {
                    throw new JeecgBootException("请填写分段租金月租金价格！");
                }
                if (DateUtils.sameDate(entity.getRentStartTime(), rent.getStartTime()) > 0) {
                    throw new JeecgBootException("分段租金开始日期不能早于合同起租时间！");
                }
                if (DateUtils.sameDate(entity.getRentEndTime(), rent.getRentEndTime()) == -1) {
                    throw new JeecgBootException("分段租金结束日期不能晚于合同结束时间！");
                }
                if (i > 0) {
                    if (DateUtils.sameDate(entity.getLeaseContractStandardRentList().get(i - 1).getRentEndTime(), rent.getStartTime()) != -1) {
                        throw new JeecgBootException("分段租金开始日期不能早于前一条的结束日期！");
                    }
                }
                i++;
            }
            entity.setLeaseContractStandardRentList(filter);
        }
        if (entity.getChargeType() == null) {
            entity.setChargeType(LeaseContractChargeTypeEnum.FIXED_PRICING.getStatus());
        }

        /**
         * 重置审批信息
         */
        entity.setProcessStatus(-1);
        entity.setProcessDescription("");
        entity.setProcessStatusText("");
    }
}
